package com.neu.yth.nepBackend.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neu.yth.nepBackend.enums.ResponseEnum;
import com.neu.yth.nepBackend.utils.Result;
import org.springframework.stereotype.Component;

/**
 * @ClassName NepSentinelBlockExceptionHandler
 * @Description
 * @Author YTH
 * @Date 2024-07-12 11:16
 */
@Component
public class NepSentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(jakarta.servlet.http.HttpServletRequest httpServletRequest,
                       jakarta.servlet.http.HttpServletResponse httpServletResponse,
                       BlockException e) throws Exception {
        Result result = null;
        if (e instanceof FlowException) {
            result = Result.fail(ResponseEnum.BLOCK_BY_FLOWEXCEPTION);
        } else if (e instanceof DegradeException) {
            result = Result.fail(ResponseEnum.LIMIT_DOWNGRADE_RESPONSE);
        } else {
            result = Result.fail(ResponseEnum.SENTINEL_EXCEPTION);
        }
        //设置响应数据格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("utf-8");
        new ObjectMapper().writeValue(
                httpServletResponse.getWriter(),
                result
        );
    }
}
